package com.xsj.client;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import jakarta.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

@Component("userChatClient")
@ClientEndpoint
public class ChatClient {

    private static final Logger log = LoggerFactory.getLogger(ChatClient.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    private Session session;
    private final String serverUri = "ws://localhost:8023/ws/chat/user/"; // manage 模块的地址和端口

    // 您需要一种方式来设置当前用户的ID，例如在用户登录后
    private Long currentUserId; 

    public void connect(Long userId) {
        if (userId == null) {
            log.error("无法连接WebSocket，用户ID为空。");
            return;
        }
        this.currentUserId = userId;
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            URI uri = new URI(serverUri + this.currentUserId);
            this.session = container.connectToServer(this, uri);
        } catch (Exception e) {
            log.error("连接到WebSocket服务器失败: {}", e.getMessage());
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        log.info("用户端连接成功: {}", session.getId());
    }

    @OnMessage
    public void onMessage(String message) {
        // 这里处理从商家收到的消息
        log.info("收到来自商家的消息: {}", message);
        // 在这里，您可以将消息通过事件、回调或其他方式通知业务层进行处理
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        this.session = null;
        log.info("用户端连接关闭: {}, 原因: {}", session.getId(), reason);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户端WebSocket发生错误", error);
    }

    /**
     * 发送消息给商家
     * @param merchantId 目标商家的ID
     * @param content 消息内容
     */
    public void sendMessageToMerchant(Long merchantId, String content) {
        if (this.session == null || !this.session.isOpen()) {
            log.warn("WebSocket连接未建立或已关闭，无法发送消息。");
            // 您可以在这里添加重连逻辑
            // connect(this.currentUserId);
            return;
        }

        try {
            Map<String, Object> payload = new HashMap<>();
            payload.put("toType", "merchant");
            payload.put("toId", merchantId);
            payload.put("content", content);

            String message = objectMapper.writeValueAsString(payload);
            this.session.getBasicRemote().sendText(message);
            log.info("向商家 {} 发送消息: {}", merchantId, content);
        } catch (JsonProcessingException e) {
            log.error("构建消息JSON失败", e);
        } catch (IOException e) {
            log.error("发送消息失败", e);
        }
    }
} 